'use strict';
module.exports = {
	/**
	 * 检查最新的invite_code和tfid,如果有变化就更新用户信息
	 */
	main: async (event) => {
		const db = uniCloud.database();

		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid,
			invite_code,
			tfid,
			advertiser_id,
			req_id,
			promotion_id,
			creativeid,
			creativetype,
			clickid,
			projectid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		console.log("38alldata========", data);
		console.log("38alldata========", userInfo);

		//添加虚拟人物
		let id = await vk.baseDao.add({
			dbName: "uni-id-users", // 表名
			dataJson: { // 需要新增的数据 json格式
				nickname: `虚拟人${userInfo._id || 0}`,
				old_id: userInfo._id || 0,
				platform: userInfo.platform || 0,
				register_date: userInfo.register_date || 0,
				middleman_id: userInfo.middleman_id || 0,
				appname: userInfo.appname || 0,
				appid: userInfo.appid || 0,
				invite_code: userInfo.invite_code || 0,
				tfid: userInfo.tfid || 0,
				clickid: userInfo.clickid || 0,
				clue_token: userInfo.clue_token || 0, //如果是抖音平台，且从本地带来了clickid，则需要更新clue_token
				ad_id: userInfo.advertiser_id || 0, //广告账号ID
				promotion_id: userInfo.promotion_id,
				advertiser_id: userInfo.advertiser_id || 0,
				douyinxnr: 1
			}
		});


		// 查询代理商的详细信息，进而获取机构id
		let agent_info = await db.collection('uni-id-users').doc(invite_code).get()
		let middleman_id = 0;
		if (agent_info.data.length == 1) {
			middleman_id = agent_info.data[0].middleman_id;
		}

		let update = await db.collection('uni-id-users').doc(uid).update({
			middleman_id: middleman_id,
			invite_code: invite_code,
			tfid: tfid,
			//以下为新增参数
			advertiser_id: advertiser_id,
			req_id: req_id,
			promotion_id: promotion_id,
			creativeid: creativeid,
			creativetype: creativetype,
			clickid: clickid,
			projectid: projectid,
			register_date: new Date().getTime(),
		})

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}